from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.neighbors import KNeighborsClassifier
from sklearn.metrics import accuracy_score

# 加载 iris 数据集
iris = load_iris()
features, labels = iris.data, iris.target
target_names = iris.target_names
# 将数据集划分为训练集 (80%) 和测试集 (20%)
features_train, features_test, labels_train, labels_test = \
    train_test_split(features, labels, test_size=0.2, random_state=80)
# 创建 KNN 分类器, 设置近邻数为 5
knn_classifier = KNeighborsClassifier(n_neighbors=5)
# 通过训练集训练模型
knn_classifier.fit(features_train, labels_train)
# 对测试集进行预测
labels_test_predict = knn_classifier.predict(features_test)
# 基于测试集预测结果对预测模型的准确率进行评估
accuracy = accuracy_score(labels_test, labels_test_predict)
print("模型准确率:", accuracy)
# 使用模型预测未知种类的鸢尾花
features_unknown = [[1.5, 3, 5.8, 2.2], [6.2, 2.9, 4.3, 1.3]]
labels_predict = knn_classifier.predict(features_unknown)
predicted_species = [target_names[label] for label in labels_predict]
print("预测的未知种类的鸢尾花: ", predicted_species)
